<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(1);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;
$task_types = $_GET['type'] ?? null;
$taskWhere = ['ORDER'=>['id'=>'ASC']];
if ($task_types){
    $taskWhere = ['ORDER'=>['id'=>'ASC'],'type' => $task_types];
}

$tasks = $DB->select('game_tasks', '*', $taskWhere);
if ($tasks){
    foreach ($tasks as $k => $v){
        $tasks[$k]['batch'] = '';
        $reward = json_decode($v['reward'],true);
        foreach ($reward as $val){
            if (isset($val['extra'])){
                $tasks[$k]['batch'] = $val['extra'];
            }
        }
    }
}

$redis_task = $REDIS->hGetAll('TASK_DATA');

$action = $_GET['action'] ?? null;
if ($action == 'del') {
    checkFunc(2, '权限不足，无法操作');
    $aid = $_GET['tid'] ?? null;
    if (!$aid) {
        goExit('game_task.php?error=无效的任务ID');
    } else {
        $DB->delete('game_tasks', ['id' => $aid]);
        $msg = '删除';
        operate_log('game_tasks', 'delete', ['ID' => $aid]);
    }
    goExit('game_task.php?success=任务'.$msg.'成功'.'&type='.$_GET['type']);
    exit;
}else if($action == 'edit') {
    checkFunc(2, '权限不足，无法操作');
    $tid = $_POST['edit_id'] ?? null;
    $name = $_POST['name'] ?? '';
    $desc = $_POST['desc'] ?? '';
    $icon = $_POST['oss_filename'] ?? '';
    $location = $_POST['location'] ?? '';
    $btn_type = $_POST['btn_type'] ?? '';
    $siliao = $_POST['siliao'] ?? '';
    $yhq = $_POST['yhq'] ?? '';
    $type2 = $_POST['type2'] ?? '';
//    if(!$tid) goExit('game_task.php?error=无效的任务ID');
    $edit_data = [
        'name' => $name,
        'desc' => $desc,
        'jump' => $location,
        'btn_type' => $btn_type,
        'type2' => $type2,
    ];

    $reward_arr = [];
    if($siliao > 0) $reward_arr[] = ['num'=>intval($siliao),'type'=>1,'id'=>1];
    if($yhq) $reward_arr[] = ['extra'=>implode('-',$yhq),'type'=>2];
    if(!empty($reward_arr)) $edit_data['reward'] = json_encode($reward_arr);

    if($icon) $edit_data['iconUrl'] = $CDN_URL . '/exchangeItemAvatar/'. $icon;
    if(!$tid){
        $edit_data['tt'] = 1;
        $edit_data['type'] = 4;
        $edit_data['daily'] = 1;
        $edit_data['count'] = 1;
        $edit_data['cond'] = 1;
        $edit_data['target'] = 1;
        $edit_data['tomorrow'] = 1;
        $DB->insert('game_tasks',$edit_data);
        $msg = '添加';
    }else{
        $edit = $DB->update('game_tasks', $edit_data, ['id'=>$tid]);
        $DB->update('game_tasks', ['status'=>'on'], ['id'=>$tid]);
        $msg = '修改';
    }
    $all_task = $DB->select('game_tasks', '*', ['status'=>'on']);
    $td = [];
    foreach($all_task as $t) {
        $t['id'] = intval($t['id']);
        $t['tt'] = intval($t['tt']);
        $t['type'] = intval($t['type']);
        $t['daily'] = intval($t['daily']);
        $t['count'] = intval($t['count']);
        $t['target'] = intval($t['target']);
        $t['type2'] = intval($t['type2']);
        $td[$t['id']] = json_encode($t);
    }
    $REDIS->del('TASK_DATA');
    $REDIS->hmset('TASK_DATA', $td);
    goExit('game_task.php?success=任务'.$msg.'成功'.'&type='.$_POST['task_types']);
    exit;
}
else if($action == 'online') {
    checkFunc(2, '权限不足，无法操作');
    $tid = $_GET['tid'] ?? null;
    if(!$tid) {
        goExit('game_task.php?error=无效的任务ID');
    }
    $save = $DB->update('game_tasks', ['status'=>'on'], ['id'=>$tid]);
    $all_task = $DB->select('game_tasks', '*', ['status'=>'on']);
    $td = [];
    foreach($all_task as $t) {
        $t['id'] = intval($t['id']);
        $t['tt'] = intval($t['tt']);
        $t['type'] = intval($t['type']);
        $t['daily'] = intval($t['daily']);
        $t['count'] = intval($t['count']);
        $t['target'] = intval($t['target']);
        $t['type2'] = intval($t['type2']);
        $td[$t['id']] = json_encode($t);
    }
    $REDIS->del('TASK_DATA');
    $REDIS->hmset('TASK_DATA', $td);
    operate_log('task', 'task_online', ['任务ID'=>$tid]);
    goExit('game_task.php?type='.$task_types);
}
else if($action == 'offline') {
    checkFunc(2, '权限不足，无法操作');
    $tid = $_GET['tid'] ?? null;
    if(!$tid) {
        goExit('game_task.php?error=无效的任务ID');
    }
    $DB->update('game_tasks', ['status'=>'off'], ['id'=>$tid]);
    $all_task = $DB->select('game_tasks', '*', ['status'=>'on']);
    $td = [];
    foreach($all_task as $t) {
        $t['id'] = intval($t['id']);
        $t['tt'] = intval($t['tt']);
        $t['type'] = intval($t['type']);
        $t['daily'] = intval($t['daily']);
        $t['count'] = intval($t['count']);
        $t['target'] = intval($t['target']);
        $t['type2'] = intval($t['type2']);
        $td[$t['id']] = json_encode($t);
    }
    $REDIS->del('TASK_DATA');
    $REDIS->hmset('TASK_DATA', $td);
    operate_log('task', 'task_offline', ['任务ID'=>$tid]);
    goExit('game_task.php?type='.$task_types);
}

$task_type = [1=>'装扮任务（进度累计）', '正常任务（进度累计）', '持续时间任务', '连续登陆任务', '每获取任务', '满足初始化条件任务'];
$task_type_2 = [1=>'日常任务', 2=>'活动任务'];

$all_item = $DB->select('game_item', '*');
$item_types = [1=>'饲料', 2=>'批次号', 5=>'装扮'];
$all_items = [];
foreach($all_item as $i) {
    $all_items[$i['id']] = $i;
}

$coupon_arr = $DB->select('game_sign_coupon','*');

display_header();
?>
<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    .task_td {cursor:pointer;}
    .valid_task {background:#ffe; /* #C2ECA7 */;}
    .task_checkbox {display:none;}
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">

    <?php display_title('任务管理'); ?>

    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-warning">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-tasks"></i> 任务列表</h3>
            <span style="margin-left:20px;">
                <?php if ($task_types == 4){ ?> <button class="btn btn-primary new_task">添加任务</button> <?php }?>
            </span>
        </div>
        <div class="box-body">
            <?php
            if(!is_array($tasks) || empty($tasks)) {
                echo '任务配置表读取失败';
            } else {
                ?>
                <table id="logtable" class="table table-bordered table-striped dataTable table-hover table-condensed" role="grid" aria-describedby="example1_info">
                    <thead>
                    <tr>
                        <th class="center" width="60">ID</th>
                        <th class="center" width="50">图标</th>
                        <th class="center" width="160">名称</th>
                        <th class="center">介绍</th>
                        <th class="center" width="120">条件</th>
                        <th class="center" width="500">完成奖励</th>
                        <th class="center" width="160">类型</th>
                        <th class="center" width="160">任务分类</th>
                        <th class="center" width="260">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    foreach($tasks as $task) {
                        $valid = $task['status'] == 'on' ? 1 : 0;
                        ?>
                        <tr role="row" style="height:38px;text-align:center;">
                            <td class="font12 <?php if($valid==1) echo 'valid_task'; ?>">
                                <span class="tid" style="font-size:16px;font-weight:bold;"><?php echo $task['id']; ?></span>
                                <?php if($valid==1) echo '<div style="color:#999;">已激活</div>'; ?>
                            </td>
                            <td class="font12">
                                <img src="<?php echo $task['iconUrl']; ?>" width="45" height="45" />
                            </td>
                            <td class="font12 tname"><?php echo $task['name']; ?></td>
                            <td class="font12 tdesc left"><?php echo $task['desc']; ?></td>
                            <td class="font12"><?php echo $task['cond']; ?></td>
                            <td class="font12 left">
                                <span style="display:none" class="treward"><?php echo $task['reward']; ?></span>
                                <?php
                                $task_reward = json_decode($task['reward'], true);
                                echo '<ul style="margin:0;padding:0;margin-left:20px;">';
                                foreach($task_reward as $tw) {
                                    if($tw['type'] == 1) {
                                        echo '<li>' . $all_items[$tw['id']]['name'] . ' * ' . $tw['num'] . '</li>';
                                    } else if($tw['type'] == 2) {
                                        echo '<li>批次号<ul style="margin:0;padding:0;margin-left:40px;">';
                                        $ex_arr = explode(',', $tw['extra']);
                                        foreach($ex_arr as $ex) {
                                            echo '<li>' . $ex . '</li>';
                                        }
                                        echo '</ul></li>';
                                    }
                                }
                                echo '</ul>';
                                ?>
                            </td>
                            <input type="hidden" class="item_batch" value="<?php echo $task['batch'] ?>">
                            <input type="hidden" class="item_btn_type" value="<?php echo $task['btn_type'] ?>">
                            <td class="font12 ttype"><?php echo $task_type[$task['type']]; ?></td>
                            <td class="font12 ttype teyp2"  type2id="<?php echo $task['type2']; ?>" ><?php echo $task_type_2[$task['type2']]; ?></td>
                            <td style="padding:0;" tid="<?php echo $task['id']; ?>">
                                <?php if($valid==1) { ?><button class="btn btn-warning btn-sm task_offline">下架</button>
                                <?php } else { ?><button class="btn btn-success btn-sm task_online">上架</button><?php } ?>
                                |
                                <button class="btn btn-default btn-sm edit_task">修改</button>

                                <?php if ($task_types == 4 && $task['id'] > 2017){ ?>| <button class="btn btn-danger del_task">删除</button> <?php }?>
                                <input type="hidden" class="tlocation" value="<?php echo $task['jump']; ?>" />
                                <input type="hidden" class="ticon" value="<?php echo $task['iconUrl']; ?>" />
                            </td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            <? } ?>
        </div>
    </div>

    <!-- 修改任务 -->
    <div class="modal fade" id="modal-edit-task">
        <div class="modal-dialog modal-lg">
            <form id="edit_task" action="game_task.php?action=edit" method="post">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                        <h4 class="title">添加任务</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="edit_id" name="edit_id" value="" />
                        <input type="hidden" id="task_types" name="task_types" value="<?php echo $task_types; ?>">
                        <table border="0" width="100%" class="modal_table_style">
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">任务ID：</th>
                                <td><span style="font-size:16px;font-weight:bold;" id="tttiiiddd"></span></td>
                            </tr>
                            <tr height="110">
                                <th style="text-align:right;padding-right:10px;">图标:</th>
                                <td>
                                    <img style="float:left;border:0px solid #aaa;" id="avatar_preview" src="images/noimage.jpg" width="100" height="100" />
                                    <div id="drop-area" style="float:left; padding-top:40px; margin-left:20px;">
                                        <label for="fileinp">
                                            <span id="text" style="padding:10px 20px;border-radius:4px;background:#007bff;color:#fff;">请上传图片</span>
                                            <input type="file" id="fileinp" />
                                            <br />
                                            <div style="margin-top:15px;font-size:12px;font-weight:normal;" id="upload_result"></div>
                                            <input type="hidden" id="oss_filename" name="oss_filename" value="" />
                                        </label>
                                    </div>
                                </td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">标题:</th>
                                <td><input type="text" class="form-control" size="20" name="name" id="name" /></td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">任务描述:</th>
                                <td><input type="text" class="form-control" size="20" name="desc" id="desc" /></td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">跳转链接:</th>
                                <td><input type="text" class="form-control" size="20" name="location" id="location" /></td>
                                </td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">类型:</th>
                                <td><input type="text" class="form-control" size="20" name="btn_type" id="btn_type" /></td>
                                </td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">分类:</th>
                                <td>
                                    <select class="form-control" name="type2" id="type2" style="display:inline !important;float:left;width:auto;">
                                        <?php foreach($task_type_2 as $ui => $un) { ?><option value="<?php echo $ui; ?>"><?php echo $un; ?></option><?php } ?>
                                    </select>
                                </td>
                                </td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">
                                    奖励饲料:
                                    <br><span style="color:#999;font-weight:normal;font-size:12px;">无饲料奖励请留空</span>
                                </th>
                                <td>
                                    <input type="number" class="form-control" style="display:inline;width:300px;" size="20" name="siliao" id="siliao" />
                                </td>
                            </tr>
                            <tr height="45" class="edit_show">
                                <th width="150" style="text-align:right;padding-right:10px;">
                                    优惠券批次号:
                                    <br><span style="color:#999;font-weight:normal;font-size:12px;">无优惠券奖励请留空</span>
                                </th>
                                <td>
                                    <!--                                    <input type="text" class="form-control" size="20" name="yhq" id="yhq" style="margin-top:20px;" />-->
                                    <div class="funcs_box" style="overflow-y:scroll;height:100px;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                        <?php
                                        echo '<div class="pull-left">';
                                        foreach ($coupon_arr as $val){
                                            echo '<label style="margin-right:15px;display:inline-block;">';
                                            echo '<input type="checkbox" name="yhq[]" value="'.$val['batch_number'].'"> ';
                                            echo $val['batch_number'];
                                            echo '</label>';
                                        }
                                        echo '</div>';
                                        echo '<div style="clear:both"></div>';
                                        echo '</div>';
                                        ?>
                                        <!--                                    <div style="font-family:Consolas;text-align:left;color:#999;font-size:12px;font-weight:normal; margin-top:10px;">-->
                                        <!--                                        格式举例：<br>-->
                                        <!--                                        A-B-C,D-E,F-G-H-I-G<br>-->
                                        <!--                                        即共获得3张券，第一张从A B C内随机，第二张从D E内随机<br>-->
                                        <!--                                        注意 - 和 , 为英文半角；A到G都是优惠券的批次号-->
                                        <!--                                    </div>-->
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary submit_form">确定</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script src="js/jquery.dm-uploader.min.js"></script>
<script type="text/javascript">
    $(function() {
        var _is_edit = false;

        $('.submit_form').click(function() {
            $('#edit_task').submit();
        });

        $('.new_task').click(function() {
            $('.title').text('添加任务');
            $('#edit_id').val('');
            $('#name').val('');
            $('#desc').val('');
            $('#location').val('');
            $('#avatar_preview').prop('src','images/noimage.jpg');
            $('#tttiiiddd').text('');
            $('#siliao').val('');
            $('#btn_type').val('');

            $("#type2 option").each(function() {
                if($(this).text().length < 1) {
                    $(this).attr('selected', true);
                }
            });
            $("input[type=checkbox]").prop("checked", "");
            $('.edit_show').hide();
            $('#modal-edit-task').modal({
                backdrop: 'static',
            });
        });

        $('.edit_task').click(function() {
            $('.title').text('修改任务');
            var tid = $(this).parent().parent().find('.tid').text();

            $('#edit_id').val(tid);
            $('#name').val($(this).parent().parent().find('.tname').text());
            $('#desc').val($(this).parent().parent().find('.tdesc').text());
            $('#location').val($(this).parent().parent().find('.tlocation').val());
            $('#tttiiiddd').text(tid);
            $('#avatar_preview').attr('src', $(this).parent().parent().find('.ticon').val());
            var btn_type = $(this).parent().parent().find('.item_btn_type').val();
            $('#btn_type').val(btn_type);

            var treward = $(this).parent().parent().find('.treward').text();
            var rewards = JSON.parse(treward);
            for(i in rewards) {
                if(rewards[i]['type'] == 1) {
                    $('#siliao').val(rewards[i]['num']);
                } else if(rewards[i]['type'] == 2) {
                    $('#yhq').val(rewards[i]['extra']);
                }
            }
            $('.edit_show').show();
            var batch = $(this).parent().parent().find('.item_batch').val();
            batch_arr = batch.split('-');
            $('input[type=checkbox]').each(function () {
                let checked = false;
                let val = $(this).val();
                if ($.inArray(val.toString(),batch_arr) > -1){
                    checked = true;
                }
                $('input:checkbox[value='+val+']').prop('checked',checked);
            });

            var type_id = $(this).parent().parent().find('.teyp2').attr('type2id');
            $("#type2 option").each(function() {
                if($(this).val() == type_id) {
                    $(this).attr('selected', true);
                }
            });

            $('#modal-edit-task').modal({
                backdrop: 'static',
            });
        });
        $("#drop-area").dmUploader({
            url: 'exchange_item.php?action=upload',
            multiple: false,
            maxFileSize: 3000000,
            allowedTypes: 'image/*',
            extFilter: ['jpg','jpeg','png','gif'],
            onInit: function(){
                console.log('Callback: Plugin initialized');
            },
            onNewFile: function(id, file){
                // When a new file is added using the file selector or the DnD area
                console.log('New file added #' + id);
                if (typeof FileReader !== "undefined"){
                    var reader = new FileReader();
                    var img = $('#avatar_preview');
                    reader.onload = function (e) {
                        img.attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            },
            onBeforeUpload: function(id){
                console.log('start upload ... ' + id);
            },
            onUploadProgress: function(id, percent){
                console.log(id + ' uploading ... ' + percent);
            },
            onUploadSuccess: function(id, data){
                var darr = data.split('|');
                if(darr[0] != 'OK') {
                    alert(darr[1]);
                } else {
                    $('#upload_result').text('图片上传成功，文件名：' + darr[1]);
                    $('#oss_filename').val(darr[1]);
                }
            },
            onUploadError: function(id, xhr, status, message){
                alert('图片上传失败，请联系管理员');
            },
            onFileSizeError: function(file){
                alert('图片不可超过3M');
            },
            onFileTypeError: function(file){
                alert('图片类型错误');
            },
            onFileExtError: function(file){
                alert('图片扩展名错误');
            }
        });

        $('.task_online').click(function() {
            var tid = $(this).parent().attr('tid');
            var task_types = $('#task_types').val();
            if(confirm('确认将这个任务发布到线上吗？')) {
                location.href = 'game_task.php?action=online&tid='+tid+'&type='+task_types;
            }
        });
        $('.task_offline').click(function() {
            var tid = $(this).parent().attr('tid');
            var task_types = $('#task_types').val();
            if(confirm('确认将这个任务从线上撤下吗？')) {
                location.href = 'game_task.php?action=offline&tid='+tid+'&type='+task_types;
            }
        });

        $('.confirm_edit').click(function() {
            var _tasks = [];
            $("input:checkbox:checked").each(function() {
                _tasks.push($(this).val());
            });
            var task_str = _tasks.join(',');
            if(confirm('确认修改有效任务为：\n==========================================\n'
                + task_str + "\n==========================================\n"
                + "注意，已完成未领取奖励的任务，如果不在新的任务列表内，将会消失！")) {
                location.href = 'game_task.php?action=edit&tasks='+task_str;
            }
        });

        $('.task_checkbox').click(function() {
            if(!_is_edit) return false;
            if($(this).is(':checked')) {
                $(this).parent().addClass('valid_task');
                //$(this).attr('checked', false);
            } else {
                $(this).parent().removeClass('valid_task');
                //$(this).attr('checked', true);
            }
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);

        $('.del_task').click(function() {
            var tid = $(this).parent().attr('tid');
            var task_types = $('#task_types').val();
            if(confirm('确认删除吗？\n\n！！！！！ 该操作不可恢复 ！！！！！\n\n')) {
                location.href = 'game_task.php?action=del&tid='+tid+'&type='+task_types;
            }
        });
    });
</script>

</body>
</html>
